<template>
  <div class="markdown-body" v-html="renderedContent"></div>
</template>

<script setup>
import { ref, computed, watch, onMounted, nextTick } from "vue";
import { marked } from "marked";
import hljs from "highlight.js";
import "highlight.js/styles/atom-one-dark.css";
import MarkdownIt from "markdown-it";
import CodeBlock from './CodeBlock.vue';

// 配置markdown-it
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  breaks: true, // 启用换行转换为<br>
  highlight: function (str, lang) {
    // 使用特殊注释来标记代码块，之后会替换成CodeBlock组件
    return `<pre class="code-block-container" data-lang="${lang || ''}"><code>${md.utils.escapeHtml(str)}</code></pre>`;
  },
});

const props = defineProps({
  content: {
    type: String,
    default: "",
  },
});

// 配置marked
marked.setOptions({
  gfm: true, // 启用GitHub风格的Markdown
  breaks: true, // 将回车转换为<br>
  highlight: function (code, lang) {
    try {
      if (lang && hljs.getLanguage(lang)) {
        return hljs.highlight(code, { language: lang }).value;
      } else {
        return hljs.highlightAuto(code).value;
      }
    } catch (e) {
      console.error("高亮显示失败:", e);
      return code;
    }
  },
});

// 预处理Markdown文本以修复常见格式问题
const preprocessMarkdown = (text) => {
  if (!text) return "";
  
  let result = text;
  
  // 1. 修复标题格式问题 - 确保#与文本之间有空格
  result = result.replace(/^(#{1,6})([^#\s])/gm, "$1 $2");
  
  // 2. 修复列表项问题 - 确保.后面有空格形成列表项
  result = result.replace(/^(\s*)\.([\S])/gm, "$1- $2");
  
  // 3. 处理段落间距，确保适当的空行
  result = result.replace(/\n{3,}/g, "\n\n");
  
  // 4. 修复无序列表项格式 - 确保-后有空格
  result = result.replace(/^(\s*)-([^\s])/gm, "$1- $2");
  
  // 5. 移除之前会导致中文乱码的非ASCII字符处理
  
  // 6. 确保标题后有空行
  result = result.replace(/^(#{1,6}[^\n]*)\n([^#\n])/gm, "$1\n\n$2");
  
  // 7. 修复有序列表项格式
  result = result.replace(/^(\s*)(\d+)\.([^\s])/gm, "$1$2. $3");
  
  // 8. 修复特殊的Markdown中无法识别的Unicode字符问题
  // 只处理已知的问题字符，使用Unicode编码表示
  result = result.replace(/\ufffd/g, " "); // 替换Unicode替换字符(U+FFFD)
  
  return result;
};

const renderedContent = computed(() => {
  try {
    // 预处理Markdown内容
    const preprocessed = preprocessMarkdown(props.content || "");
    
    // 使用markdown-it渲染内容
    const rendered = md.render(preprocessed);
    
    // 后处理：修复可能的嵌套列表问题
    return rendered.replace(/<\/li>\s*<li>/g, "</li>\n<li>");
  } catch (e) {
    console.error("Markdown-it渲染失败:", e);
    // 如果markdown-it失败，回退到marked
    try {
      return marked(preprocessMarkdown(props.content || ""));
    } catch (e) {
      console.error("Marked渲染也失败:", e);
      return props.content || "";
    }
  }
});

// 替换代码块为CodeBlock组件
const replaceCodeBlocks = () => {
  nextTick(() => {
    const codeContainers = document.querySelectorAll('.markdown-body .code-block-container');
    
    codeContainers.forEach(container => {
      // 如果已经处理过，跳过
      if (container.getAttribute('data-processed') === 'true') return;
      
      const lang = container.getAttribute('data-lang') || '';
      const code = container.querySelector('code')?.innerText || '';
      
      try {
        // 创建CodeBlock组件
        const codeBlockEl = document.createElement('div');
        codeBlockEl.className = 'custom-code-block';
        
        // 简单渲染代码块
        codeBlockEl.innerHTML = `
          <div class="code-block-header">
            <span class="code-language">${lang || 'text'}</span>
            <button class="copy-button">复制</button>
          </div>
          <pre class="code-content"><code class="language-${lang || 'text'}">${code}</code></pre>
        `;
        
        // 添加复制功能
        const copyButton = codeBlockEl.querySelector('.copy-button');
        if (copyButton) {
          copyButton.addEventListener('click', () => {
            navigator.clipboard.writeText(code)
              .then(() => {
                copyButton.textContent = '已复制';
                setTimeout(() => {
                  copyButton.textContent = '复制';
                }, 2000);
              });
          });
        }
        
        // 替换原始代码块
        if (container.parentNode) {
          container.parentNode.replaceChild(codeBlockEl, container);
        }
        
        // 标记为已处理
        container.setAttribute('data-processed', 'true');
      } catch (error) {
        console.error('代码块替换失败:', error);
      }
    });
  });
};

// 当内容变化时，替换代码块
watch(
  () => props.content,
  () => {
    setTimeout(replaceCodeBlocks, 100);
  }
);

onMounted(() => {
  setTimeout(replaceCodeBlocks, 100);
});
</script>

<style>
.markdown-body {
  color: inherit;
  line-height: 1.6;
  word-wrap: break-word;
}

/* 标题 */
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
  margin-top: 1.5em;
  margin-bottom: 0.5em;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body h1 {
  font-size: 2em;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.3em;
}
.markdown-body h2 {
  font-size: 1.5em;
  border-bottom: 1px solid #eee;
  padding-bottom: 0.3em;
}
.markdown-body h3 {
  font-size: 1.25em;
}
.markdown-body h4 {
  font-size: 1em;
}
.markdown-body h5 {
  font-size: 0.875em;
}
.markdown-body h6 {
  font-size: 0.85em;
  color: #6a737d;
}

/* 段落和间距 */
.markdown-body p,
.markdown-body ul,
.markdown-body ol,
.markdown-body blockquote,
.markdown-body table {
  margin-bottom: 1em;
}

/* 链接 */
.markdown-body a {
  color: #0366d6;
  text-decoration: none;
}

.markdown-body a:hover {
  text-decoration: underline;
}

.markdown-body strong {
  font-weight: 600;
}

/* 列表 */
.markdown-body ul,
.markdown-body ol {
  padding-left: 2em;
  margin-top: 0.5em;
  margin-bottom: 1em;
}

.markdown-body ul ul,
.markdown-body ul ol,
.markdown-body ol ul,
.markdown-body ol ol {
  margin-top: 0;
  margin-bottom: 0;
}

.markdown-body li + li {
  margin-top: 0.25em;
}

.markdown-body li {
  margin-bottom: 0.2em;
}

/* 块引用 */
.markdown-body blockquote {
  padding: 0 1em;
  color: #6a737d;
  border-left: 0.25em solid #dfe2e5;
  margin-left: 0;
  margin-right: 0;
}

/* 代码 */
.markdown-body code:not(.hljs) {
  padding: 0.2em 0.4em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(27, 31, 35, 0.05);
  border-radius: 3px;
  font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
}

.markdown-body pre {
  padding: 16px;
  overflow: auto;
  font-size: 85%;
  line-height: 1.45;
  background-color: #f6f8fa;
  border-radius: 3px;
}

.markdown-body pre > code {
  padding: 0;
  margin: 0;
  font-size: 100%;
  word-break: normal;
  white-space: pre;
  background: transparent;
  border: 0;
}

/* 表格 */
.markdown-body table {
  border-collapse: collapse;
  width: 100%;
  overflow: auto;
  display: block;
  margin-top: 0.5em;
  margin-bottom: 1em;
}

.markdown-body table th {
  font-weight: 600;
}

.markdown-body table th,
.markdown-body table td {
  padding: 6px 13px;
  border: 1px solid #dfe2e5;
}

.markdown-body table tr {
  background-color: #fff;
  border-top: 1px solid #c6cbd1;
}

.markdown-body table tr:nth-child(2n) {
  background-color: #f6f8fa;
}

/* 图片 */
.markdown-body img {
  max-width: 100%;
  box-sizing: content-box;
  background-color: #fff;
}

/* 水平线 */
.markdown-body hr {
  height: 0.25em;
  padding: 0;
  margin: 24px 0;
  background-color: #e1e4e8;
  border: 0;
}

/* 代码块样式 */
.custom-code-block {
  margin: 1em 0;
  border-radius: 6px;
  overflow: hidden;
  background-color: #282c34;
  color: #abb2bf;
}

.code-block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0.5em 1em;
  background-color: #21252b;
  color: #abb2bf;
  font-family: monospace;
  font-size: 0.9em;
}

.code-language {
  text-transform: uppercase;
  font-size: 0.85em;
  opacity: 0.7;
}

.copy-button {
  background-color: transparent;
  border: 1px solid #444;
  color: #abb2bf;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 0.8em;
  cursor: pointer;
  transition: all 0.2s;
}

.copy-button:hover {
  background-color: #444;
  color: #fff;
}

.code-content {
  margin: 0;
  padding: 1em;
  overflow-x: auto;
}

.code-content code {
  background-color: transparent !important;
  padding: 0 !important;
  font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
}

/* 黑暗模式 */
@media (prefers-color-scheme: dark) {
  .markdown-body pre,
  .markdown-body code {
    background-color: #2d333b;
  }

  .markdown-body blockquote {
    border-left-color: #444c56;
    color: #8b949e;
  }

  .markdown-body table th,
  .markdown-body table td {
    border-color: #373e47;
  }

  .markdown-body table tr {
    background-color: #21262d;
    border-top-color: #373e47;
  }

  .markdown-body table tr:nth-child(2n) {
    background-color: #161b22;
  }

  .markdown-body hr {
    background-color: #444c56;
  }

  .markdown-body a {
    color: #2f81f7;
  }
  
  .custom-code-block {
    background-color: #1e2227;
  }
  
  .code-block-header {
    background-color: #191d22;
  }
  
  .copy-button {
    border-color: #333;
    color: #aaa;
  }
  
  .copy-button:hover {
    background-color: #333;
  }
}
</style>
